package com.zhengb.flink.study.datastream;

import lombok.extern.slf4j.Slf4j;
import org.apache.flink.api.common.functions.FlatMapFunction;
import org.apache.flink.api.java.tuple.Tuple2;
import org.apache.flink.streaming.api.datastream.DataStream;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.windowing.time.Time;
import org.apache.flink.util.Collector;

/**
 * socket stream 统计单次出现次数
 *
 * @author zhengbo
 * @date 2019/12/18
 */
@Slf4j
public class WindowWordCount {

    public static class Splitter implements FlatMapFunction<String, Tuple2<String, Integer>> {

        @Override
        public void flatMap(String input, Collector<Tuple2<String, Integer>> out) throws Exception {

            String[] split = input.split(" ");
            for (String s : split) {
                out.collect(new Tuple2<>(s, 1));
            }
        }
    }

    public static void main(String[] args) throws Exception {

        StreamExecutionEnvironment executionEnvironment = StreamExecutionEnvironment.getExecutionEnvironment();

        executionEnvironment.setParallelism(5);

//        executionEnvironment.socketTextStream("10.0.10.36", 9999)
//                .flatMap(new Splitter()).addSink(
//                new RichSinkFunction<Tuple2<String, Integer>>() {
//
//                    @Override
//                    public void invoke(Tuple2<String, Integer> value, Context context) throws Exception {
//                        log.info("sinkValue:{}", value);
//                    }
//                });

        DataStream<Tuple2<String, Integer>> dataStream = executionEnvironment
                .socketTextStream("10.0.10.36", 9999)
                .flatMap(new Splitter()).keyBy(0).timeWindow(Time.seconds(5)).sum(1);

        dataStream.print();

        executionEnvironment.execute("WindowWordCount");

    }
}
